import requests
from bs4 import BeautifulSoup
import csv
import os


def __get_html__():

    curr_path = os.getcwd()
    # print(curr_path)
    # 发送requests请求
    response = requests.get("https://arena.5eplay.com/data")
    html = response.content
    return html



def __get_soup__():
    # 用BeautifulSoup解析网页
    soup = BeautifulSoup(__get_html__(), "html.parser")


# 假设我们想要找到的是名为"odd-even data-rank"的表格
    table = soup.find('table', attrs={"class": "odd-even data-rank"})

# 打开一个文件用于写入CSV
    with open('player_data.csv', 'w', newline='', encoding='utf-8') as csvfile:
        # 创建一个csv writer对象
        writer = csv.writer(csvfile)

        # 写入列名
        writer.writerow(['玩家', '国家（地区）', '天梯分'])

        # 遍历表格的每一行
        for row in table.find_all("tr"):
            cols = row.find_all('td')
            # 确保我们不是在处理表头或其他非数据行
            if cols:
                # 新建一个字典用来存储选手信息
                player_data = {}
                # 假设rank是在第23个td的span标签中
                rank_span = cols[22].find('span')
                # 可以输出一下看看
                # print(rank_span.text)
                if rank_span:
                    player_rank = rank_span.text.replace(" ", "")
                else:
                    player_rank = ""  # 如果没有找到rank，设置为空字符串

                # 假设name是在第二个td的a标签中
                name_a = cols[1].find('a')
                if name_a:
                    player_name = name_a.text

                else:
                    player_name = ""  # 如果没有找到name，设置为空字符串

                # 假设country信息在另一个td中，你需要根据实际的HTML结构来定位它
                country_i = cols[1].find('i')
                # print(country_i)
                # 提取class属性
                class_attr = country_i['class']
                # print(class_attr)
                player_country = class_attr[-1]
                # print(player_country)

                # 将数据写入CSV文件
                writer.writerow([player_name, player_country, player_rank])

if __name__ == '__main__':
    soup = __get_soup__()